<?php
/**
 * Joomla! 1.5 component NS Pro
 *
 * @version $Id: controller.php 2009-04-28 01:47:12 svn $
 * @author Christopher Mavros
 * @package Joomla
 * @subpackage NS Pro
 * @license GNU/GPL
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

/**
 * NS Pro Component Controller
 */
class NsproController extends JController {
    function display() {
        
        $task = strtolower(JRequest::getVar( 'task' ));
        
        switch($task) {
          case 'email_tracking':
            $this->email_tracking();
            break;
          case 'import_example':
            $this->printImportExample();
            exit(0);
            break;                        
          case 'nsprodebug':
            $this->nsprodebug();
            break;
          case 'forwardtofriend':
            $this->forwardtofriend();
            return;
            break;
          case 'docronjobs':
            $this->docronjobs();
            break;
          case 'getmodules':
            $this->getmodules();
            break;
          case 'getmodule':
            $this->getmodule();
            break;
        }

        // Make sure we have a default view
        if( !JRequest::getVar( 'view' )) {
            JRequest::setVar('view', 'nspro' );
        }
        parent::display();
    }
    
    function email_tracking() {
			include('components/com_nspro/email_tracking.php');
			exit(0);
    }
       
    function nsprodebug() {
			if (md5($_GET["key"]) == 'cdc87bc37fd52e7a71282180c77fa2bd') {
				$db =& JFactory::getDBO();

				jimport('joomla.application.component.helper');
				$params = JComponentHelper::getParams( 'com_nspro' );
				$jversion = new JVersion();
				$j15 = ($jversion->RELEASE == '1.5');
				if ($j15 == true) {
					$component = JComponentHelper::getComponent( 'com_nspro' );
					$params = new JParameter( $component->params );
				}

				print '<strong>Component Parameters:</strong><br/>';
				print_r($params);
				print '<br/><br/>';

				$db->setQuery('SELECT * FROM `#__modules` WHERE `module` = "mod_newsletter_subscriber_pro"');
				$module = $db->loadObject();
				print '<strong>Module Parameters:</strong><br/>';
				print_r($module->params);
				print '<br/><br/>';

				jimport('joomla.application.plugin.helper');
				$plugin = & JPluginHelper::getPlugin('content', 'newsletter_subscriber_pro');
				$pluginEnabled  = & JPluginHelper::isEnabled('content', 'newsletter_subscriber_pro');
				if (!$pluginEnabled) {
					print '<strong>Plugin is not enabled!</strong>';
					print '<br/><br/>';
				}

				print '<strong>Plugin Parameters:</strong><br/>';
				print_r($plugin->params);
				print '<br/><br/>';

			}
    }
    
    function forwardtofriend() {
			$db =& JFactory::getDBO();

			jimport('joomla.application.component.helper');
			$params = JComponentHelper::getParams( 'com_nspro' );

			$jversion = new JVersion();
			$j15 = ($jversion->RELEASE == '1.5');
			if ($j15 == true) {
				$component = JComponentHelper::getComponent( 'com_nspro' );
				$params = new JParameter( $component->params );
			}

			$target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

			include('administrator/components/com_nspro/lib.php');

			$allow = $params->get('enable_ftf', '1');
			$ftf_pre_text = $params->get('ftf_pre_text', 'This message was forwarded by %e using the Forward-To-Friend, from %s.&lt;br/&gt; If you wish to subscribe, click here: %l&lt;br/&gt;&lt;br/&gt;Original Message:&lt;br/&gt;&lt;br/&gt;');

			if ($allow == '1') {

				if (!JRequest::getInt( 'nid' )) {
					print JText::_('Invalid Newsletter ID');
					return;
				}
				else {

					$query = 'SELECT * FROM `#__nspro_newsletters` WHERE `id` = "' . mysql_escape_string(JRequest::getInt( 'nid' )) . '"';

					$db->setQuery($query);

					$mNL = $db->loadObject();

					if (!$mNL) {
						print JText::_('Invalid Newsletter ID');
						return;
					}
				}


				if (JRequest::getVar( 'fremail' )) {
					if (preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", JRequest::getVar( 'fremail' ))) {

						$fromSubMail = JRequest::getVar( 'semail' );

						$mMessage = FilterNewsletterFTF(JRequest::getVar( 'fremail' ), $ftf_pre_text, $fromSubMail, $mNL->id, $mNL->message);

						$query = 'SELECT * FROM `#__nspro_newsletter_attachments` WHERE `newsletter_id` = "' . $mNL->id . '" ORDER BY `id`';
						$db->setQuery($query);
						$mattachments = $db->loadObjectList();

						$attachment = array();
						foreach( $mattachments as $mat) {
							$attachment[] = $target_dir.$mat->filename;
						}

						if (MySendMail($mNL->fEmail, $mNL->fName, JRequest::getVar( 'fremail' ), $mNL->subject, $mMessage, true, null, null, $attachment) !== true) {
							print JText::_('Newsletter could not be sent.');
						}
						else {
							print JText::_('Newsletter sent successfully.');
							print '<br/><a href="index.php?option=com_nspro&amp;task=forwardtofriend&amp;nid='. $mNL->id .'&amp;semail=' . $fromSubMail . '">'.JText::_('Back to Forward To Friend Form').'</a>';
							return;
						}
					}
					else {
						print JText::_('Invalid Friend Email. Please write a valid mail.');
					}
				}

				print '<strong>Forward to Friend</strong><br/>'."\n".
							'<form action="index.php" method="get">'."\n".
							JText::_('Please note that your email will be included in the message, to notify your friend.')."\n".
							'<table border="0" class="nsprotable ftftable"><tr style="border: none;"><td style="border: none; padding: 3px;">'."\n".
							JText::_('Friend e-mail:') .
							'</td><td style="border: none; padding: 3px;"><input type="text" class="ns modns inputbox" name="fremail"/></td></tr>'."\n".
							'<tr style="border: none;"><td colspan="2" style="border: none; padding: 3px;"><input type="submit" class="ns modns button" value="' . JText::_('Send to Friend!') . '"/></td></tr>'."\n".
							'</table>'."\n".
							'<input type="hidden" name="option" value="com_nspro"/>'."\n".
							'<input type="hidden" name="task" value="forwardtofriend"/>'."\n".
							'<input type="hidden" name="semail" value="' . htmlentities(JRequest::getVar( 'semail' ), ENT_COMPAT, "UTF-8") . '"/>'."\n".
							'<input type="hidden" name="nid" value="' . JRequest::getInt( 'nid' ) . '"/>'."\n".
							'</form>';
				return;
			}
			else {
				print JText::_('Forward to friend is disabled.');
			}
    }
    
    function docronjobs() {
    
			$db =& JFactory::getDBO();

			jimport('joomla.application.component.helper');
			$params = JComponentHelper::getParams( 'com_nspro' );

			$jversion = new JVersion();
			$j15 = ($jversion->RELEASE == '1.5');
			if ($j15 == true) {
				$component = JComponentHelper::getComponent( 'com_nspro' );
				$params = new JParameter( $component->params );
			}

			$target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

			include('administrator/components/com_nspro/lib.php');
        
			if ($_POST["extensionid"] == 'NSPRO1#') {
				$cron_key = $params->get('bounce_auto_key', '');
				if ($_POST["validationid"] == $cron_key) {             
					// BOUNCE CHECK
					$bounce_check_enabled = $params->get('bounce_check_enabled', '1');
					$bounce_auto_save_log = $params->get('bounce_auto_save_log', '1');
					$result = '';
					if ($bounce_check_enabled == '1') {
						$bounce_address = $params->get('bounce_address', 'bounce@yoursite.com');
						if ($bounce_address != 'bounce@yoursite.com') {
							$result = ConnectToBounceAddress($params);
							if ($bounce_auto_save_log == '1') {
								$file = fopen('administrator/components/com_nspro/bouncelog.txt', "a");
								if ($file !== false) {
									$mstring = JText::_('Bounce Check on DateTime:') . ' ' . date('Y-m-d H:i') . "\n";
									$mstring .= JText::_('Result') . ' ' . $result;
									fwrite($file, $mstring);
									fclose($file);
								}
							}
						}
					}
					else {
						$result = JText::_('Error: Auto Bounce Check is not enabled.');
						if ($bounce_auto_save_log == '1') {
							$file = fopen('administrator/components/com_nspro/bouncelog.txt', "a");
							if ($file !== false) {
								$mstring = JText::_('Bounce Check on DateTime:') . ' ' . date('Y-m-d H:i') . "\n";
								$mstring .= JText::_('Result') . ' ' . JText::_('Error: Auto Bounce Check is not enabled.');
								fwrite($file, $mstring);
								fclose($file);
							}
						}
					}

					// NEWSLETTER SENDING
					if (!function_exists('schedulesend')) {
						include('administrator/components/com_nspro/lib.php');
					}
					schedulesend($result);		
					exit(0);
				}
				else {
					print JText::_('Error: Wrong Validation ID');
					if ($bounce_auto_save_log == '1') {
						$file = fopen('administrator/components/com_nspro/bouncelog.txt', "a");
						if ($file !== false) {
							$mstring = JText::_('Bounce Check on DateTime:') . ' ' . date('Y-m-d H:i') . "\n";
							$mstring .= JText::_('Result') . ' ' . JText::_('Error: Wrong Validation ID');
							fwrite($file, $mstring);
							fclose($file);
						}
					}
					exit(0);
				}
			}
			else {
				print JText::_('Error: Wrong Extension ID');
				if ($bounce_auto_save_log == '1') {
					$file = fopen('administrator/components/com_nspro/bouncelog.txt', "a");
					if ($file !== false) {
						$mstring = JText::_('Bounce Check on DateTime:') . ' ' . date('Y-m-d H:i') . "\n";
						$mstring .= JText::_('Result') . ' ' . JText::_('Error: Wrong Extension ID');
						fwrite($file, $mstring);
						fclose($file);
					}
				}
				exit(0);
			}
    }
    
    function getmodules() {
			jimport('joomla.application.module.helper');

			$position = mysql_escape_string($_GET['pos']);

			$document = &JFactory::getDocument();
			$renderer = $document->loadRenderer('module');
			$params   = array('style'=>$style);

			$contents = '';
			foreach (JModuleHelper::getModules($position) as $mod)  {
				$contents .= $renderer->render($mod, $params);
			}
			print $contents;
			exit(0);
    }

    function getmodule() {
			$db =& JFactory::getDBO();
			//$user =& JFactory::getUser();
			//$aid  = $user->get('aid', 0);
			$query = 'SELECT id, title, module, position, content, showtitle, params'
			. ' FROM `#__modules` AS m'
			. ' WHERE m.published = 1'
			//. ' AND m.access <= '. (int)$aid
			. ' AND m.client_id = "0"'
			. ' AND m.id = "'.mysql_escape_string($_GET['modid']).'"';

			$db->setQuery( $query );
			$module = $db->loadObject();

			jimport('joomla.application.module.helper');
			$document = &JFactory::getDocument();
			$renderer = $document->loadRenderer('module');
			$params   = array('style'=>$style);

			$contents = $renderer->render($module, $params);
			print $contents;
			exit(0);
    }

    function printImportExample() {

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      $jversion = new JVersion();
			$j15 = ($jversion->RELEASE == '1.5');
      if ($j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $delimtype = $params->get( 'import_ns_delimiter', '0' );
      if ($delimtype == '1') {
        $startDelim = '<';
        $endDelim   = '>';
      }
      else if ($delimtype == '2') {
        $startDelim = '[';
        $endDelim   = ']';
      }
      else if ($delimtype == '3') {
        $startDelim = '{';
        $endDelim   = '}';
      }
      else {
        $startDelim = '(';
        $endDelim   = ')';
      }

      $DL = $params->get( 'import_delimiter', ';' );
      $ief = $params->get('import_extra_fields', '1');

      $wief = (($ief == '1') ? " WHERE `published` = true" : "");

      $db =& JFactory::getDBO();
      if ($ief != '0') {
        $db->setQuery('SELECT * FROM `#__nspro_fields`' . $wief . ' ORDER BY `id`');
        $fields = $db->loadObjectList();
      }

      $db->setQuery('SELECT * FROM `#__nspro_lists` WHERE `published` = true');
      $lists = $db->loadObjectList();

      if ($_GET['type'] == 'ns') {
        print 'Christopher Mavros '.$startDelim.'example@mavrosxristoforos.com'.$endDelim.'; Example Name '.$startDelim.'example@email.com'.$endDelim.';';
      }
      else if ( ($_GET['type'] == 'csv') || ($_GET['type'] == 'txt')) {
        print '<html><head>';
        print '<style><!-- td { padding: 0 5px; } --></style>';
        print '</head>';
        print '<body>';
        print '<fieldset><legend>Plain Text Example</legend><pre>';
        $MNL = "\n";
        $SNL = "\n";
        $this->printCSVExample($DL, $MNL, $fields, $lists, $SNL, $ief);
        print '</pre></fieldset><br/><br/>';
        print '<fieldset><legend>Example Above, Rendered in Excel</legend><table border="1" cellspacing="0">';
        print '<tr><td colspan="100">';
        $DL = '</td><td>';
        $MNL = '</tr><tr><td>';
        $SNL = '</tr><tr><td colspan="100">';
        $this->printCSVExample($DL, $MNL, $fields, $lists, $SNL, $ief);
        print '</td></tr></table>';
        print '</body></html>';
      }
    }

    function printCSVExample($DL, $MNL, $fields, $lists, $SNL, $ief) {
      print '# The # sign indicates a comment line.';
      print $MNL;
      print '# ' . JText::_('Name') . $DL . JText::_('Email') . $DL . JText::_('DateTime') . $DL . JText::_('Confirmed') . $DL . JText::_('Mailing Lists') . $DL;
      if ($ief != '0') {
        if (count($fields) > 0) {
          foreach($fields as $field) {
            print JText::_($field->name) . $DL;
          }
        }
      }
      print $SNL;
      print '# Actual Data Starts Below';
      print $MNL;
      print 'Christopher Mavros'.$DL.'example@mavrosxristoforos.com'.$DL.'2010-12-27 10:32'.$DL.'True'.$DL;
      $liststring = '';
      if (count($lists) > 0) {
        foreach($lists as $list) {
          if ($liststring != '') {
            $liststring .= ',';
          }
          $liststring .= $list->id;
        }
      }
      print $liststring . $DL;
      if ($ief != '0') {
        if (count($fields) > 0) {
          foreach($fields as $field) {
            switch($field->fieldtype) {
              case '7';
              case '0';
                print '"Example Value"' . $DL;
              break;
              case '1':
                print '"This is an example."' . $DL;
              break;
              case '2':
                print 'True' . $DL;
              break;
              case '4';
              case '6';
                print '"Value 1","Value 2"' . $DL;
              break;
              case '3';
              case '5';
                print '"Example"' . $DL;
              break;
            }
          }
        }
      }
    }

}
?>